﻿using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Xml;
using Microsoft.Win32;

namespace Oxage.Common
{
	public partial class Config
	{
		#region Members
		private static bool defaultCache = false;
		private static IConfigSource defaultSource = ConfigSources.Registry;
		private static Hashtable htCache = new Hashtable(); //Cached variables
		#endregion

		#region Properties
		/// <summary>
		/// Gets or sets the flag that defines if variable is cached by default (if not explicitly specified).
		/// </summary>
		public static bool DefaultCache
		{
			get { return defaultCache; }
			set { defaultCache = value; }
		}

		/// <summary>
		/// Gets or sets the property that defines default ConfigSource (if not explicitly specified).
		/// </summary>
		public static IConfigSource DefaultSource
		{
			get { return defaultSource; }
			set { defaultSource = value; }
		}

		/// <summary>
		/// Gets or sets a registry root path.
		/// </summary>
		public static string RegistryRootPath
		{
			get
			{
				return ((RegistryConfig)Config.ConfigSources.Registry).RegistryRootPath;
			}
			set
			{
				((RegistryConfig)Config.ConfigSources.Registry).RegistryRootPath = value;
			}
		}

		/// <summary>
		/// Gets or sets a registry key (e.g. local machine, current user).
		/// </summary>
		public static RegistryKey DefaultRegistryKey
		{
			get
			{
				return ((RegistryConfig)Config.ConfigSources.Registry).DefaultRegistryKey;
			}
			set
			{
				((RegistryConfig)Config.ConfigSources.Registry).DefaultRegistryKey = value;
			}
		}
		#endregion

		#region Getters
		public static bool Get(string key, out string value)
		{
			return Get(key, out value, defaultCache, defaultSource);
		}

		public static bool Get(string key, out string value, bool cache, IConfigSource source)
		{
			value = null;
			bool completed = false;

			if (cache)
			{
				if (htCache.Contains(key))
				{
					value = (string)htCache[key];
					completed = true;
				}
				else
				{
					completed = source.Get(key, out value);
					htCache.Add(key, value);
				}
			}
			else
			{
				completed = source.Get(key, out value);
			}

			return completed;
		}

		public static bool Get(string key, out int value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = int.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out int value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = int.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out byte value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = byte.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out byte value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = byte.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out short value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = short.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out short value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = short.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out long value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = long.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out long value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = long.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out double value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = double.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out double value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = double.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out bool value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = bool.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out bool value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = bool.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out TimeSpan value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = TimeSpan.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out TimeSpan value, bool cache, IConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = TimeSpan.TryParse(temp, out value);
			return parsed && converted;
		}
		#endregion

		#region Setters
		public static void Set(string key, string value)
		{
			Set(key, value, defaultCache, defaultSource);
		}

		public static void Set(string key, string value, bool cache, IConfigSource source)
		{
			source.Set(key, value);

			//Save to cache
			if (cache)
			{
				if (htCache.Contains(key))
				{
					//Update
					htCache[key] = value;
				}
				else
				{
					//Insert
					htCache.Add(key, value);
				}
			}
		}

		public static void Set(string key, int value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, int value, bool cache, IConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set(string key, double value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, double value, bool cache, IConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set(string key, bool value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, bool value, bool cache, IConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set(string key, TimeSpan value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, TimeSpan value, bool cache, IConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set<T>(string key, T value)
		{
			if (value != null)
			{
				Set(key, value.ToString());
			}
			else
			{
				Clear(key);
			}
		}

		public static void Set<T>(string key, T value, bool cache, IConfigSource source)
		{
			if (value != null)
			{
				Set(key, value.ToString(), cache, source);
			}
			else
			{
				Clear(key, source);
			}
		}
		#endregion

		#region Cleaners
		public static void Clear(string key)
		{
			DefaultSource.Clear(key);
		}

		public static void Clear(string key, IConfigSource source)
		{
			if (htCache.Contains(key))
			{
				htCache.Remove(key);
			}
			source.Clear(key);
		}

		public static void ClearCache()
		{
			htCache = new Hashtable();
		}
		#endregion

		#region Exists
		public static bool Exists(string key)
		{
			return DefaultSource.Exists(key);
		}

		public static bool Exists(string key, IConfigSource source)
		{
			return source.Exists(key);
		}
		#endregion

		#region Samples
#if COMMENT
		internal static void Sample()
		{
			//Sample #1
			Config.DefaultCache = true; //Cache automatically
			Config.DefaultSource = ConfigSource.Registry; //Read/write to registry

			//Sample #2
			string path = null;
			Config.Get("Path", out path); //Read Path entry from registry

			//Sample #3
			TimeSpan syncTime = TimeSpan.Zero;
			Config.Get("SyncTime", out syncTime, false, ConfigSource.AppConfig); //Read SyncTime entry from AppConfig

			//Sample #4
			Config.Set("Flag", true); //Set Flag to true in registry

			//Sample #5
			Config.Clear("Flag"); //Delete Flag entry from registry

			//Sample #6
			Config.ImportXmlConfig(@"D:\Temp\Config.xml");
			Config.Set(@"Common\Path", @"D:\inetpub\www\project\", false, ConfigSource.Xml); //Path key in Common folder
			Config.ExportXmlConfig(@"D:\Temp\Config.xml");

			//Sample #7
			Config.Clear("Flag"); //Delete Flag entry from registry

			//Sample #8
			int count = 0;
			Config.Get(@"Shop\Articles\Count", out count, true, ConfigSource.Registry); //Get Count key from Shop\Articles from cache if possible or registry folder if does not exist in cache
		}
#endif
		#endregion

		public static string[] GetKeys(string path)
		{
			string[] result = new string[0];

			RegistryKey reg = DefaultRegistryKey.OpenSubKey(RegistryRootPath + path);
			if (reg != null)
			{
				result = reg.GetValueNames();
				reg.Close();
			}

			return result;
		}
	}

	public partial class Config
	{
		public static class ConfigSources
		{
			private static IConfigSource appConfig;
			private static IConfigSource regConfig;
			private static IConfigSource xmlConfig;

			/// <summary>
			/// Configuration from app.config file, appSettings section.
			/// </summary>
			public static IConfigSource AppConfig
			{
				get
				{
					if (appConfig == null)
					{
						appConfig = new ProgramConfig();
					}
					return appConfig;
				}
			}

			/// <summary>
			/// Configuration from Windows Registry, path defined in RegistryRootPath property.
			/// </summary>
			public static IConfigSource Registry
			{
				get
				{
					if (regConfig == null)
					{
						regConfig = new RegistryConfig();
					}
					return regConfig;
				}
			}

			/// <summary>
			/// Configuration from in-memory XML document.
			/// </summary>
			public static IConfigSource XmlConfig
			{
				get
				{
					if (xmlConfig == null)
					{
						xmlConfig = new XmlConfig();
					}
					return xmlConfig;
				}
			}
		}
	}

	public interface IConfigSource
	{
		bool Get(string key, out string value);
		bool Set(string key, string value);
		void Clear(string key);
		bool Exists(string key);
		bool Import(string path);
		bool Export(string path);
	}

	internal class ProgramConfig : IConfigSource
	{
		#region IConfigSource Members
		public bool Get(string key, out string value)
		{
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key
			value = ConfigurationManager.AppSettings[key];
			return true;
		}

		public bool Set(string key, string value)
		{
			//Nothing to set in App.config
			return false;
		}

		public void Clear(string key)
		{
		}

		public bool Exists(string key)
		{
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key
			return (ConfigurationManager.AppSettings[key] != null);
		}

		public bool Import(string path)
		{
			return false;
		}

		public bool Export(string path)
		{
			return false;
		}
		#endregion
	}

	internal class RegistryConfig : IConfigSource
	{
		#region Members
		private const string CONFIG_DEFAULT_REGISTY_PATH = @"Software\Oxage\unknown\";
		private string registryRootPath = CONFIG_DEFAULT_REGISTY_PATH;
		private RegistryKey registryKey = Registry.CurrentUser;
		#endregion

		#region Properties
		/// <summary>
		/// Gets or sets a registry root path.
		/// </summary>
		public string RegistryRootPath
		{
			get
			{
				return registryRootPath;
			}
			set
			{
				if (!string.IsNullOrEmpty(value))
				{
					if (!value.EndsWith("\\"))
					{
						value += "\\";
					}
					registryRootPath = value;
				}
			}
		}

		/// <summary>
		/// Gets or sets a registry key (e.g. local machine, current user).
		/// </summary>
		public RegistryKey DefaultRegistryKey
		{
			get
			{
				return registryKey;
			}
			set
			{
				registryKey = value;
			}
		}
		#endregion

		#region IConfigSource Members
		public bool Get(string key, out string value)
		{
			bool completed = false;
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			value = null;
			RegistryKey reg = DefaultRegistryKey.OpenSubKey(RegistryRootPath + path);
			if (reg != null)
			{
				value = (string)reg.GetValue(pkey);
				reg.Close();
				completed = true;
			}

			return completed;
		}

		public bool Set(string key, string value)
		{
			bool completed = false;
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			RegistryKey reg = DefaultRegistryKey.CreateSubKey(RegistryRootPath + path);
			if (reg != null)
			{
				reg.SetValue(pkey, value);
				reg.Close();
				completed = true;
			}

			return completed;
		}

		public void Clear(string key)
		{
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			try
			{
				RegistryKey reg = DefaultRegistryKey.OpenSubKey(RegistryRootPath + path, true);
				if (reg != null && reg.GetValue(pkey) != null)
				{
					reg.DeleteValue(pkey);
					reg.Close();
				}
			}
			catch
			{
				//Exception if key does not exist
			}
		}

		public bool Exists(string key)
		{
			bool result = false;
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key
			RegistryKey reg = DefaultRegistryKey.OpenSubKey(RegistryRootPath + path);
			if (reg != null)
			{
				result = ((string)reg.GetValue(pkey) != null);
				reg.Close();
			}
			return result;
		}

		public bool Import(string path)
		{
			//TODO: Import .reg file
			return false;
		}

		public bool Export(string path)
		{
			//TODO: Create .reg file
			return false;
		}
		#endregion
	}

	internal class XmlConfig : IConfigSource
	{
		//NOTE: This class is not fully implemented nor tested

		#region Members
		private const string CONFIG_ENTRY_XPATH = "//Configuration//Region[@Path='{0}']//Entry[@Key='{1}']";
		private const string CONFIG_REGION_XPATH = "//Configuration//Region[@Path='{0}']";
		private static XmlDocument xmlCache = null; //Cached xml config file
		#endregion

		#region IConfigSource Members
		public bool Get(string key, out string value)
		{
			value = null;
			bool completed = false;
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			string xpath = string.Format(CONFIG_ENTRY_XPATH, path, pkey);
			XmlNode node = xmlCache.SelectSingleNode(xpath);
			if (node != null)
			{
				value = (node.Attributes["Value"] != null ? node.Attributes["Value"].Value : null);
				completed = true;
			}

			return completed;
		}

		public bool Set(string key, string value)
		{
			bool completed = false;
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			if (xmlCache != null)
			{
				//Create xpath to check if entry with the same key already exists
				string xpath = string.Format(CONFIG_ENTRY_XPATH, path, pkey);
				XmlNode node = xmlCache.SelectSingleNode(xpath);

				//Update existing node
				if (node != null)
				{
					if (node.Attributes["Value"] != null)
					{
						//Update Value attribute
						node.Attributes["Value"].Value = value;
					}
					else
					{
						//Insert Value attribute
						XmlAttribute valueAttribute = xmlCache.CreateAttribute("Value");
						valueAttribute.Value = value;
						node.Attributes.Append(valueAttribute);
					}
				}
				//Create a new node
				else
				{
					xpath = string.Format(CONFIG_REGION_XPATH, path);
					node = xmlCache.SelectSingleNode(xpath);

					//If region node is missing
					if (node == null)
					{
						node = xmlCache.CreateElement("Region");
						XmlAttribute pathAttribute = xmlCache.CreateAttribute("Path");
						pathAttribute.Value = path;
						node.Attributes.Append(pathAttribute);
						xmlCache.AppendChild(node);
					}

					//Append Entry node
					XmlElement entry = xmlCache.CreateElement("Entry");
					entry.SetAttribute("Key", pkey);
					entry.SetAttribute("Value", value);
					node.AppendChild(entry);
				}
			}

			return completed;
		}

		public void Clear(string key)
		{
		}

		public bool Exists(string key)
		{
			return false;
		}

		public bool Import(string path)
		{
			bool completed = false;
			XmlDocument doc = new XmlDocument();
			doc.Load(path);
			if (doc.DocumentElement.LocalName == "Configuration")
			{
				xmlCache = doc;
				completed = true;
			}

			//if (doc != null && doc.DocumentElement.LocalName == "Configuration")
			//{
			//  xmlCache = doc;
			//}

			return completed;
		}

		public bool Export(string path)
		{
			bool completed = false;
			if (xmlCache != null)
			{
				xmlCache.Save(path);
				completed = true;
			}
			return completed;
		}
		#endregion
	}
}
